<template>
    <a-modal :keyboard="false" :maskClosable="false" title="表单" :open="visible" width="50%" :confirmLoading="loading"
        centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="24">
                <a-col :span="24">
                    <a-form-item label="系统名称" v-bind="validateInfos.name">
                        <a-input v-model:value="modelRef.name" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="24">
                <a-col :span="24">
                    <a-form-item label="关联角色角色" v-bind="validateInfos.roleIds">
                        <a-select v-model:value="modelRef.roleIds" :options="dictData.rolesList" mode="multiple"
                            placeholder="请关联角色" style="width: 100%"
                            :field-names="{ label: 'name', value: 'id', options: 'children' }"></a-select>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, nextTick } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { createTenant, updateTenant, getTenant } from '@/api/user/tenant';
    import { cloneDeep, isUndefined, isEmpty } from 'lodash-es';
    import { getRoleAll } from '@/api/user/role';
    import type { UpdateTenantParams } from '@/api/user/tenant';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<UpdateTenantParams | null>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const dictData = reactive<any>({
                jobsData: [],
                menuData: [],
                rolesList: [],
            });
            const defaultForm = {
                name: '',
                roleIds: [],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                name: [{ required: true, message: '请输入系统名称' }],
                roleIds: [{ required: true, message: '请选择关联角色' }],
            });

            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    getRoleAll().then(res => {
                        if (!isEmpty(res.data)) {
                            dictData.rolesList = res.data;
                        }
                    });
                    if (props.model) {
                        Object.assign(modelRef, props.model);
                        // 这一步可以不用，直接传递 model.permissions 到页面进行渲染
                        // 这里重新组装是为了演示结构不相同情况下可以按照下列方案组装结构
                        getTenant(props.model.id).then(res => {
                            nextTick(() => {
                                const { roleIds } = res.data;
                                Object.assign(modelRef, res.data, {
                                    roleIds: isEmpty(roleIds) ? [] : roleIds,
                                });
                            });
                        });
                    }
                }
            });

            const filterOption = (inputValue: string, option: any) => {
                return option.title.includes(inputValue);
            };

            const handleCancel = () => {
                resetFields();
                emit('cancel');
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;
                    const { roleIds, ...lastData } = modelRef;
                    (isUndefined(modelRef.id) ? createTenant : updateTenant)({
                        ...lastData,
                        roleIds: roleIds,
                    })
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };

            return {
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,

                dictData,
                filterOption,

                isUndefined,
            };
        },
    });
</script>
